package com.data.controllers;

import com.data.controllers.response.BaseResponse;
import com.data.dto.CV;
import com.data.util.PoiUtil;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/")
public class PoiController {

    @RequestMapping("/createWord")
    @ResponseBody
    @CrossOrigin
    public void downloadFile(@RequestBody CV cv, String fileName, HttpServletResponse response) {

        InputStream ins = PoiUtil.createWord(cv);
        try {
            BufferedInputStream br = new BufferedInputStream(ins);
            byte[] buf = new byte[1024];
            int len = 0;
            response.reset();
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setContentType("application/octet-stream;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName + ".docx", "utf-8") + "\"");
            OutputStream ou = response.getOutputStream();
            while ((len = br.read(buf)) > 0) {
                ou.write(buf, 0, len);
            }
            br.close();
            ou.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }
    }

    @RequestMapping("/uploadImage")
    @ResponseBody
    @CrossOrigin
    public BaseResponse uploadImage(@RequestParam(value = "base64Data", defaultValue = "") String base64Data) {
        if(base64Data == "") return BaseResponse.error("base64数据为空！");
        base64Data = base64Data.replaceAll(" ", "+");
        base64Data = base64Data.replaceFirst("data:image/png;base64,", "");
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            byte[] b = decoder.decodeBuffer(base64Data);
            for(int i=0;i<b.length;i++)
            {
                if(b[i]<0)
                {
                    b[i]+=256;
                }
            }
            String name = UUID.randomUUID().toString()+System.currentTimeMillis()%1000+".png";
            File newFile = new File("D:/"+name);
            if (!newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdir();
            }
            if (newFile.exists()) {
                newFile.delete();
            }
            OutputStream out = new FileOutputStream(newFile);
            out.write(b);
            out.flush();
            out.close();
            return BaseResponse.build(newFile.getAbsolutePath(),1);
        } catch (IOException e) {
            return BaseResponse.error("base64数据转换为图片发生异常");
        }
    }
}